﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.BusinessEntity.YunZhiJia;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using LiMinCRMPlugin.InterfaceDocking;
using Kingdee.BOS.BusinessEntity.BusinessFlow;

namespace LiMinCRMPlugin
{
    /// <summary>
    /// 应收收款核销记录反核销删除计划插件
    /// </summary>
    /// <remarks>
    /// 功能： 定时查询应收收款核销记录删除表。
    /// 创建人：wzx
    /// 创建日期：2024.3.28
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    [Description("应收收款核销记录反核销插件")]
    [HotUpdate]
    public class WriteOffRecordsDelete : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            //throw new NotImplementedException();
            #region 应收收款核销记录(应收与收款)
            var sql = @"/*dialect*/select t0.FID,FIsJoinMatch,FSRCBILLNO,FVERIFYDATE,FTARGETBILLNO,FCURWRITTENOFFAMOUNT,FCONTACTUNIT,FVERIFIERID,FSRCBILLID,FSRCROWID,FTargetBillID,FTargetEntryId,CRMID,FVERIFIERID FROM DeleteRECMacthLog t0 LEFT OUTER JOIN DeleteRECMacthLogENTRY t1 ON t0.FID = t1.FID 
where FIsJoinMatch=0 and FMatchFag=1  and FSOURCETYPE='180ecd4afd5d44b5be78a6efe4a7e041' and FISADIBILL=0   and (FCOMPUTEID is null or FCOMPUTEID ='') and
(SynchronizationStatus=1) and DeleteStatus=0 ";

            DataTable dt_SK = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
            foreach (DataRow reader in dt_SK.Rows)
            {
                string FID = Convert.ToString(reader["FID"]);//核销记录内码
                string FIsJoinMatch = Convert.ToString(reader["FIsJoinMatch"]);//是否为关联核销(0:非自动核销；1:自动核销)
                string FVERIFYDATE = Convert.ToString(reader["FVERIFYDATE"]);//核销日期
                string FSRCBILLNO = Convert.ToString(reader["FSRCBILLNO"]);//收款单编码
                string FTARGETBILLNO = Convert.ToString(reader["FTARGETBILLNO"]);//应收单编码
                decimal FCURWRITTENOFFAMOUNT = Convert.ToDecimal(reader["FCURWRITTENOFFAMOUNT"]);//本次核销金额本位币
                int VerifiedID = Convert.ToInt32(reader["FCONTACTUNIT"]);//核销人内码
                int CustomerID = Convert.ToInt32(reader["FVERIFIERID"]);//客户内码
                string FTargetBillID = Convert.ToString(reader["FTargetBillID"]);//收款单FID
                string FTargetEntryId = Convert.ToString(reader["FTargetEntryId"]);//收款单明细ID
                string FSRCBILLID = Convert.ToString(reader["FSRCBILLID"]);//应收单FID
                string FSRCROWID = Convert.ToString(reader["FSRCROWID"]);//应收单付款计划FENTRYID
                string CRMID = Convert.ToString(reader["CRMID"]);//CRM核销id
                string VerifiedAccount = "";//核销人用户账号
                //查询用户账号
                var sqlUser = string.Format(@"/*dialect*/select FUserAccount from T_SEC_user where FUSERID={0}", VerifiedID);
                DataTable dt_User = DBUtils.ExecuteDataSet(ctx, sqlUser).Tables[0];
                if (dt_User != null && dt_User.Rows.Count > 0 && dt_User.Rows[0]["FUserAccount"].ToString() != "")
                {
                    VerifiedAccount = Convert.ToString(dt_User.Rows[0]["FUserAccount"]);
                }
                //查询客户编码信息
                string sqlCust = string.Format(@"/*dialect*/select F_RDLV_CRMId from T_BD_CUSTOMER where FCUSTID = '{0}'", CustomerID);
                DataTable dtCust = DBUtils.ExecuteDataSet(ctx, sqlCust).Tables[0];
                int CRMCustID = 0;
                if (dtCust != null && dtCust.Rows.Count > 0 && dtCust.Rows[0]["F_RDLV_CRMId"].ToString() != "")
                {
                    CRMCustID = Convert.ToInt32(dtCust.Rows[0]["F_RDLV_CRMId"]);
                }
                //查询核销人编码信息
                string sqlStaff = string.Format(@"/*dialect*/select FNUMBER from T_HR_EMPINFO where FID = '{0}'", VerifiedID);
                DataTable dtStafft = DBUtils.ExecuteDataSet(ctx, sqlStaff).Tables[0];
                string VerifiedNo = "";
                if (dtStafft != null && dtStafft.Rows.Count > 0 && dtStafft.Rows[0]["FNUMBER"].ToString() != "")
                {
                    VerifiedNo = Convert.ToString(dtStafft.Rows[0]["FNUMBER"]);
                }

                
                //只同步自动核销的记录

                string resultSearch = CRMSearchVerificationRecords(ctx, CRMID, VerifiedAccount);
                //存在，才执行删除
                if (resultSearch == CRMID)
                {
                    string resultDelete = CRMDeleteVerificationRecords(ctx, CRMID, VerifiedAccount);
                    if (resultDelete == "删除成功")
                    {
                        #region 核销记录日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = FID;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "删除核销记录";
                        interfaceLog.FInvokeType = "";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "成功";
                        interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\""+ VerifiedAccount + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturnData = resultDelete;
                        interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\""+ VerifiedAccount + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturn = resultDelete;
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update DeleteRECMacthLogENTRY set DeleteStatus='1' 
                    where FID={0}", FID);
                        sqlList.Add(updateSql);
                        DBServiceHelper.ExecuteBatch(ctx, sqlList);
                        #endregion
                    }
                    else
                    {
                        #region 核销记录写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = FID;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "删除核销记录";
                        interfaceLog.FInvokeType = "";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "失败";
                        interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\""+ VerifiedAccount + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturnData = resultDelete;
                        interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\""+ VerifiedAccount + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturn = resultDelete;
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update DeleteRECMacthLogENTRY set DeleteStatus='0' 
                    where FID={0}", FID);
                        sqlList.Add(updateSql);
                        DBServiceHelper.ExecuteBatch(ctx, sqlList);
                        #endregion
                    }
                }
                //else
                //{
                //    #region 核销记录写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                //    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                //    interfaceLog.FBILLNO = FID;
                //    interfaceLog.FBILLID = FID;
                //    interfaceLog.FDATE = System.DateTime.Now;
                //    interfaceLog.FINTERNAME = "删除核销记录";
                //    interfaceLog.FInvokeType = "";
                //    interfaceLog.Ftoken = "";
                //    interfaceLog.FSTATUS = "失败";
                //    interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                //    interfaceLog.FReturnData = resultSearch;
                //    interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                //    interfaceLog.FReturn = resultSearch;
                //    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                //    List<string> sqlList = new List<string>();
                //    if (!string.IsNullOrEmpty(LogSql))
                //    {
                //        sqlList.Add(LogSql);
                //    }
                //    //更新单据
                //    string updateSql = string.Format(@"/*dialect*/ update DeleteRECMacthLogENTRY set DeleteStatus='0' 
                //    where FID={0}", FID);
                //    sqlList.Add(updateSql);
                //    DBServiceHelper.ExecuteBatch(ctx, sqlList);
                //    #endregion
                //}
            }
            #endregion

            #region 应收收款核销记录(应收与应收)
            var sql1 = @"/*dialect*/select t0.FID,FIsJoinMatch,FSRCBILLNO,FVERIFYDATE,FTARGETBILLNO,FPLANAMOUNT,FCURWRITTENOFFAMOUNT,FWRITTENOFFAMOUNTFOR,FCONTACTUNIT,FVERIFIERID,FSRCBILLID,FSRCROWID,FTargetBillID,FTargetEntryId,CRMID,FVERIFIERID
FROM T_AR_RECMacthLog t0 
LEFT OUTER JOIN T_AR_RECMacthLogENTRY t1 ON t0.FID = t1.FID 
where FIsJoinMatch=0 and FMatchFag=1 and FSOURCETYPE='180ecd4afd5d44b5be78a6efe4a7e041' and FTargetBillTypeId='180ecd4afd5d44b5be78a6efe4a7e041' 
and (FCOMPUTEID is not null or FCOMPUTEID <>'') and FPLANAMOUNT>0
and FISADIBILL=0  and (SynchronizationStatus=0 or SynchronizationStatus is null)";

            DataTable dt_YSYS = DBUtils.ExecuteDataSet(ctx, sql1).Tables[0];
            foreach (DataRow ys in dt_YSYS.Rows)
            {
                string FID1 = Convert.ToString(ys["FID"]);//核销记录内码
                string FIsJoinMatch1 = Convert.ToString(ys["FIsJoinMatch"]);//是否为关联核销(0:非自动核销；1:自动核销)
                string FVERIFYDATE1 = Convert.ToString(ys["FVERIFYDATE"]);//核销日期
                string FSRCBILLNO1 = Convert.ToString(ys["FSRCBILLNO"]);//应收单编码
                string FTARGETBILLNO1 = Convert.ToString(ys["FTARGETBILLNO"]);//负数应收单编码
                decimal FCURWRITTENOFFAMOUNT1 = Convert.ToDecimal(ys["FCURWRITTENOFFAMOUNT"]);//本次核销金额本位币
                decimal FPLANAMOUNT1 = Convert.ToDecimal(ys["FPLANAMOUNT"]);//应收金额本位币             
                int VerifiedID1 = Convert.ToInt32(ys["FCONTACTUNIT"]);//核销人内码
                int CustomerID1 = Convert.ToInt32(ys["FVERIFIERID"]);//客户内码
                string FSRCBILLID1 = Convert.ToString(ys["FSRCBILLID"]);//正数应收单FID
                string FSRCROWID1 = Convert.ToString(ys["FSRCROWID"]);//正数应收单明细ID                 
                string CRMYSDID1 = "";//CRM应收单ID
                int CRMCustID1 = 0;//CRM客户ID
                string CRMID1 = "";
                CRMID1 = Convert.ToString(ys["CRMID"]);//CRM核销内码
                string VerifiedAccount1 = "";//核销人用户账号
                                             //查询用户账号
                var sqlUser = string.Format(@"/*dialect*/select FUserAccount from T_SEC_user where FUSERID={0}", VerifiedID1);
                DataTable dt_User = DBUtils.ExecuteDataSet(ctx, sqlUser).Tables[0];
                if (dt_User != null && dt_User.Rows.Count > 0 && dt_User.Rows[0]["FUserAccount"].ToString() != "")
                {
                    VerifiedAccount1 = Convert.ToString(dt_User.Rows[0]["FUserAccount"]);
                }
                //查询正数应收单CRM内码信息
                var sqlReceivable1 = string.Format(@"/*dialect*/select a.F_DEV_CRMId,b.F_DEV_CRMEntryId from t_AR_receivable a
inner join T_AR_RECEIVABLEENTRY b on a.FID=b.FID
where a.FID={0}", FSRCBILLID1);
                DataTable dt_YSD1 = DBUtils.ExecuteDataSet(ctx, sqlReceivable1).Tables[0];
                if (dt_YSD1 != null && dt_YSD1.Rows.Count > 0 && dt_YSD1.Rows[0]["F_DEV_CRMId"].ToString() != "")
                {
                    CRMYSDID1 = Convert.ToString(dt_YSD1.Rows[0]["F_DEV_CRMId"]);
                }





                //查询客户CRM内码信息
                var sqlCust1 = string.Format(@"/*dialect*/select F_RDLV_CRMId from T_BD_CUSTOMER 
where FCUSTID={0}", CustomerID1);
                DataTable dt_Cust1 = DBUtils.ExecuteDataSet(ctx, sqlCust1).Tables[0];
                if (dt_Cust1 != null && dt_Cust1.Rows.Count > 0 && dt_Cust1.Rows[0]["F_RDLV_CRMId"].ToString() != "")
                {
                    CRMCustID1 = Convert.ToInt32(dt_Cust1.Rows[0]["F_RDLV_CRMId"]);
                }
                //查询核销人编码信息
                string sqlStaff1 = string.Format(@"/*dialect*/select FNUMBER from T_HR_EMPINFO where FID = '{0}'", VerifiedID1);
                DataTable dtStafft1 = DBUtils.ExecuteDataSet(ctx, sqlStaff1).Tables[0];
                string VerifiedNo1 = "";
                if (dtStafft1 != null && dtStafft1.Rows.Count > 0 && dtStafft1.Rows[0]["FNUMBER"].ToString() != "")
                {
                    VerifiedNo1 = Convert.ToString(dtStafft1.Rows[0]["FNUMBER"]);
                }



                #region 构建请求body报文
                WriteOffRecordsModel.mainlList mainTable1 = new WriteOffRecordsModel.mainlList
                {

                    rq = FVERIFYDATE1, //日期
                    yszd = CRMYSDID1,//应收单FID
                    skd = "",//收款单FID
                    ysje = FPLANAMOUNT1,//应收金额
                    skje = FCURWRITTENOFFAMOUNT1,//本次核销金额
                    khmc = CRMCustID1, //客户
                    dd = "", //订单
                    hxjlbm = FID1, //核销记录编码
                    hxr = VerifiedNo1, //核销人
                    skjhid = FSRCROWID1,//收款计划ID
                    skdmxid = "",//收款单明细ID
                    sfsx = 1
                };
                #endregion
                //只同步自动核销的记录

                string resultSearch = CRMSearchVerificationRecords(ctx, CRMID1, VerifiedAccount1);
                //存在，才执行删除
                if (resultSearch == CRMID1)
                {
                    string resultDelete = CRMDeleteVerificationRecords(ctx, CRMID1, VerifiedAccount1);
                    if (resultDelete == "删除成功")
                    {
                        #region 核销记录日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = FID1;
                        interfaceLog.FBILLID = FID1;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "删除核销记录";
                        interfaceLog.FInvokeType = "";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "成功";
                        interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\""+ VerifiedAccount1 + "y\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID1 + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturnData = resultDelete;
                        interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\""+ VerifiedAccount1 + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID1 + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturn = resultDelete;
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update DeleteRECMacthLogENTRY set DeleteStatus='1' 
                    where FID={0}", FID1);
                        sqlList.Add(updateSql);
                        DBServiceHelper.ExecuteBatch(ctx, sqlList);
                        #endregion
                    }
                    else
                    {
                        #region 核销记录写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = FID1;
                        interfaceLog.FBILLID = FID1;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "删除核销记录";
                        interfaceLog.FInvokeType = "";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "失败";
                        interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\""+ VerifiedAccount1 + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID1 + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturnData = resultDelete;
                        interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\""+ VerifiedAccount1 + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":{\"id\":\"" + FID1 + "\"}}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturn = resultDelete;
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update DeleteRECMacthLogENTRY set DeleteStatus='0' 
                    where FID={0}", FID1);
                        sqlList.Add(updateSql);
                        DBServiceHelper.ExecuteBatch(ctx, sqlList);
                        #endregion
                    }
                }


            }
            #endregion
        }

        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting(Context ctx, string InterfaceName)
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface where F_RDLV_InterfaceName='{0}'", InterfaceName);
            return DBServiceHelper.ExecuteDataSet(ctx, Sql).Tables[0];
        }

        /// <summary>
        /// CRM查询核销记录接口
        /// </summary>
        public string CRMSearchVerificationRecords(Context ctx, string code,string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/getDataByPK/select_Verification_records";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";

            DataTable dt = APISetting(ctx, "查询核销记录");
            if (dt != null)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }

            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToSearchNews(requestUri1, systemid, currentTimeTamp, md5OfStr, code,  UserAccount);


            return result;
        }

        /// <summary>
        /// CRM删除核销记录接口
        /// </summary>
        public string CRMDeleteVerificationRecords(Context ctx, string id, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/deleteModeDataByPK/delete_outbound_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting(ctx, "删除核销记录");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToDeleteNews(requestUri1, systemid, currentTimeTamp, md5OfStr, id,  UserAccount);


            return result;
        }

        /// <summary>
        /// CRM查询核销记录POST
        /// </summary>
        public static string PostToSearchNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string id, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\""+UserAccount+"\"},\"mainTable\":{\"id\":\""+id+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            //string[] resAry = result.Split(new string[] { "result" }, StringSplitOptions.None);
            //string json = resAry[resAry.Length - 1].Remove(0, 3);
            //json = json.Remove(json.Length - 2, 2);
            //json = Regex.Unescape(json);
            //if (json == "{}")
            //{
            //    return "无结果";
            //}
            //else
            //{
            //    Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
            //    Dictionary<string, object> mainTableJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(dicJson["mainTable"].ToString());
            //    string returnCode = mainTableJson["id"].ToString();
            //    return returnCode;
            //}
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            if (jo == null)
            {
                return "无结果";
            }
            else if (jo.ToString().Contains("status"))
            {
                string returnCode = jo["info"].ToString();
                return returnCode;
            }
            else if (jo["result"].ToString() == "{}")
            {
                return "无结果";
            }
            else
            {

                JToken rtToken = jo.SelectToken("result");
                JObject rt = (JObject)JsonConvert.DeserializeObject(rtToken.ToString());
                JToken mtToken = rt.SelectToken("mainTable");
                JObject mt = (JObject)JsonConvert.DeserializeObject(mtToken.ToString());
                string returnCode = mt["id"].ToString();
                return returnCode;
            }
        }

        /// <summary>
        /// CRM删除核销记录POST
        /// </summary>
        public static string PostToDeleteNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string id, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\""+UserAccount+"\"},\"mainTable\":{\"id\":\""+id+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            string[] resAry = result.Split(new string[] { "result" }, StringSplitOptions.None);
            string json = resAry[resAry.Length - 1].Remove(0, 3);
            //json = json.Remove(json.Length - 2, 2);
            json = Regex.Unescape(json);
            json = Regex.Replace(json, "\"\"", "\"");
            string[] message = json.Split(new string[] { "message" }, StringSplitOptions.None);

            if (json == "{}")
            {
                return "无结果";
            }
            else
            {

                return message[1].Substring(3, 4);
            }
        }




        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }



        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }


        /**
       * 接口返回值自定义 
       */
        public class Return
        {
            public string status { get; set; }
            public string[] datajson { get; set; }
        }


    }
}
